/*
	DS Kanji Flash
	Copyright (C) 2009,2010 Bernhard Schelling

	This file is part of DS Kanji Flash.

	DS Kanji Flash is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	DS Kanji Flash is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with DS Kanji Flash.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "global.h"
#include <time.h>

#include <exception>
//create empty terminate handler to avoid code bloat
void __gnu_cxx::__verbose_terminate_handler() { }

#define SCENEKEYACTIVITY pSceneCurrent->WantsEveryFrame+ul_keys.pressed.value+(pSceneCurrent->WantsKeyReleaseEvents ? ul_keys.released.value : 0)+(pSceneCurrent->WantsKeyHeldEvents ? ul_keys.held.value : 0)

int main()
{
  int currentFrame = 0;
	
	ulInit(UL_INIT_ALL); //Initialize uLibrary
	ulInitGfx(); //Initialize the graphical part
	ulInitText(); //Initialize the text part
	//ulInitLibFat();
	srand(time(NULL));

	//Set-up dual screen mode. Beware!!! It will eat up 2 whole banks (C-D) and force your game to run at 30 fps!
	ulInitDualScreenMode();
	
	InitTextDisplay();

	bool bDrawTop = false, bDrawBottom = false;

	cScene::GoTo(SCN_START); //, (void*)48);

	while(1)
	{
		currentFrame++;
 
		pSceneCurrent->ProcessInput();

		//Start our drawing
		ulStartDrawing2D();
		
		if (!ulGetMainLcd())
		{
			pSceneCurrent->DrawScreen_Top();
			//displayStringCenter(ul_lcdFont, itos(currentFrame), 0, 180-ul_lcdFont->charHeight, 256, COL_WHITE);
			bDrawTop = true;
		}
		else
		{
			pSceneCurrent->DrawScreen_Bottom();
			//displayStringCenter(ul_lcdFont, itos(currentFrame), 0, 180-ul_lcdFont->charHeight, 256, COL_WHITE);
			bDrawBottom = true;
		}

		
		//End the drawing
		ulEndDrawing();
		
		//Wait the VBlank (synchronize at 60 fps)
		ulSyncFrame();
		ulReadKeys(0);

		if (SCENEKEYACTIVITY != 0) bDrawTop = bDrawBottom = false;
		if (bDrawTop && bDrawBottom)
		{
			while (SCENEKEYACTIVITY == 0) { swiWaitForVBlank(); ulReadKeys(0); }
			bDrawTop = bDrawBottom = false;
		}

		if (ul_keys.pressed.lid)
		{
			unsigned long oldIE = REG_IE ;
			REG_IE = IRQ_VBLANK ;
			powerOff(POWER_LCD) ;
			swiIntrWait(1, IRQ_VBLANK);
			powerOn(POWER_LCD) ;
			REG_IE = oldIE ;
		}
	}

	return 0;
}
